/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package verification;

import java.util.Calendar;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JPanel;

/**
 *
 * @author NATHAN
 */
public class DateFieldVerifier extends AbstractValidator {

  private int length;

  public DateFieldVerifier(JPanel parent, JComponent c, String message, int length) {
    super(parent, c, message);
    this.length = length;
  }

  @Override
  protected boolean validationCriteria(JComponent c) {

    String date = ((JFormattedTextField) c).getText().replaceAll(" ", "");
    String[] splitDate = date.split("-");
    if (date.length() != length + 2) {
      switch (splitDate.length) {
        case 3:
          if (splitDate[2].length() != 2) {
            setMessage("Not a valid day.");
            ((JFormattedTextField) c).select(8, 10);
          }
        case 2:
          if (splitDate[1].length() != 2) {
            setMessage("Not a valid month.");
            ((JFormattedTextField) c).select(5, 7);
          }
        case 1:
          if (splitDate[0].length() != 4) {
            setMessage("Not a valid year.");
            ((JFormattedTextField) c).select(0, 4);
          }
        default:
          return false;
      }
    }

    int year = Integer.valueOf(splitDate[0]);
    int month = Integer.valueOf(splitDate[1]);
    int day = Integer.valueOf(splitDate[2]);
    int currentYear = Calendar.getInstance().get(Calendar.YEAR);
    int currentMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
    int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    int numDays = 0;

    if (year > currentYear || year < currentYear - 100) {
      setMessage("Not a valid year.");
      ((JFormattedTextField) c).select(0, 4);
      return false;
    }
    if (month > 12 || month < 1) {
      setMessage("Not a valid month.");
      ((JFormattedTextField) c).select(5, 7);
      return false;
    }
    if (day < 1) {
      setMessage("Not a valid day.");
      ((JFormattedTextField) c).select(8, 10);
      return false;
    }

    switch (month) {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        numDays = 31;
        break;
      case 4:
      case 6:
      case 9:
      case 11:
        numDays = 30;
        break;
      case 2:
        if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) {
          numDays = 29;
        } else {
          numDays = 28;
        }
    }
    if (day > numDays) {
      setMessage("Not a valid day");
      ((JFormattedTextField) c).select(8, 10);
      return false;
    }

    if (year == currentYear && (month > currentMonth || (month == currentMonth && day > currentDay))) {
      setMessage("Future dates are not allowed.");
      return false;
    }
    return true;
  }
}
